package com.zz.yt.lib.bluetooth.base;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.constants.INumberConstant;
import com.whf.android.jar.util.log.LatteLogger;
import com.whf.android.jar.util.storage.LattePreference;
import com.zz.yt.lib.bluetooth.R;
import com.zz.yt.lib.ui.CustomTitleBar;
import com.zz.yt.lib.ui.SwitchListLayout;
import com.zz.yt.lib.ui.base.ui.LatteTitleDelegate;

import java.util.ArrayList;


/**
 * 连接蓝牙
 *
 * @author qf
 * @version 1.0
 **/
public class ReplaceBleDelegate extends LatteTitleDelegate implements CompoundButton.OnCheckedChangeListener {

    SwitchListLayout mSwitchBt = null;
    ScrollView mScrollBle = null;
    ImageView mImageRefreshing = null;
    RecyclerView mRecyclerBtOn = null;
    RecyclerView mRecyclerBtUn = null;

    private SearchResult mSearchResult = null;
    private BluetoothClient mClient = null;
    private OnAdapter onAdapter = null;
    private UnAdapter unAdapter = null;


    @NonNull
    public static ReplaceBleDelegate create() {
        final Bundle args = new Bundle();
        final ReplaceBleDelegate fragment = new ReplaceBleDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public Object setLayout() {
        return R.layout.blu_delegate_replace_ble;
    }

    @Override
    protected void setCustomTitleBar(@NonNull CustomTitleBar titleBar) {
        titleBar.setText("蓝牙");
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        super.onBindView(savedInstanceState, rootView);

        mSwitchBt = rootView.findViewById(R.id.id_switch_bt);
        mScrollBle = rootView.findViewById(R.id.id_scroll_ble);
        mImageRefreshing  = rootView.findViewById(R.id.img_refreshing_garden);
        mRecyclerBtOn = rootView.findViewById(R.id.id_recycler_bt_on);
        mRecyclerBtUn = rootView.findViewById(R.id.id_recycler_bt_un) ;

        rootView.findViewById(R.id.img_refreshing_garden).setOnClickListener(v -> onRefreshing());

        initBluetooth();
    }

    /*****************初始化**********************/
    private void initBluetooth() {
        mClient = Bluetooth.getRestService();
        //蓝牙开关监听
        mClient.registerBluetoothStateListener(new BluetoothStateListener() {
            @Override
            public void onBluetoothStateChanged(boolean openOrClosed) {
                inSwitch(openOrClosed);
                ToastUtils.showShort(openOrClosed ? "蓝牙打开成功" : "蓝牙关闭");
                if (openOrClosed) {
                    search();
                }
            }
        });
        mClient.unregisterBluetoothStateListener(new BluetoothStateListener() {
            @Override
            public void onBluetoothStateChanged(boolean openOrClosed) {
                inSwitch(openOrClosed);
                ToastUtils.showShort(openOrClosed ? "蓝牙打开成功" : "蓝牙关闭");
                if (openOrClosed) {
                    search();
                }
            }
        });
        boolean isBt = mClient.isBluetoothOpened();
        if (isBt) {
            inSwitch(true);
            search();
        } else {
            mClient.openBluetooth();
        }
        inRecycler();
    }

    private void inRecycler() {
        mRecyclerBtOn.setLayoutManager(new LinearLayoutManager(Latte.getActivity()));
        mRecyclerBtUn.setLayoutManager(new LinearLayoutManager(Latte.getActivity()));
        onAdapter = new OnAdapter();
        onAdapter.setOnItemClickListener((adapter, view, position) -> {
            mSearchResult = onAdapter.getData().get(position);
            onConnected();
        });
        mRecyclerBtOn.setAdapter(onAdapter);
        unAdapter = new UnAdapter();
        unAdapter.setOnItemClickListener((adapter, view, position) -> {

        });
        mRecyclerBtUn.setAdapter(unAdapter);
    }

    /**
     * 默认为关闭
     *
     * @param isBt：
     */
    private void inSwitch(boolean isBt) {
        hideLoading();
        if (mSwitchBt != null) {
            mSwitchBt.getSwitchRightView().setChecked(isBt);
            mSwitchBt.getSwitchRightView().setOnCheckedChangeListener(this);
        }
        if (mScrollBle != null) {
            mScrollBle.setVisibility(isBt ? View.VISIBLE : View.INVISIBLE);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        showLoading();
        onAdapter.setList(new ArrayList<>());
        unAdapter.setList(new ArrayList<>());
        if (isChecked) {
            mClient.openBluetooth();
        } else {
            mClient.closeBluetooth();
        }
    }

    /****************扫描及连接设备********************/
    void onRefreshing() {
        onAdapter.setList(new ArrayList<>());
        unAdapter.setList(new ArrayList<>());
        search();
    }

    private void search() {
        SearchRequest request = new SearchRequest.Builder()
                // 再经典蓝牙2s
                .searchBluetoothClassicDevice(2000)
                // 再扫BLE设备
                .searchBluetoothLeDevice(5000)
                // 再扫BLE设备2s
                .searchBluetoothClassicDevice(3000)
                .build();
        mClient.search(request, new SearchResponse() {

            @Override
            public void onSearchStarted() {
                LatteLogger.i("扫描蓝牙设备");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                LatteLogger.json(GsonUtils.toJson(device));
                if (device.rssi == INumberConstant.ZERO) {
                    onAdapter.addData(device);
                } else {
                    unAdapter.addData(device);
                }
            }

            @Override
            public void onSearchStopped() {
                LatteLogger.i("搜索停止");
            }

            @Override
            public void onSearchCanceled() {
                LatteLogger.i("搜索取消");
            }
        });
    }

    private void onConnected() {
        mClient.stopSearch();
        LattePreference.addCustomAppProfile(Bluetooth.BLUETOOTH, mSearchResult.getName());
        LattePreference.addCustomAppProfile(Bluetooth.BLUETOOTH_ADDRESS, mSearchResult.getAddress());
        LatteLogger.i(mSearchResult.getName() + ">>>" + mSearchResult.getAddress());
        getSupportDelegate().setFragmentResult(Activity.RESULT_OK, null);
        getSupportDelegate().pop();
    }

    /**
     * 我的设备
     */
    static class OnAdapter extends BaseQuickAdapter<SearchResult, BaseViewHolder> {

        private OnAdapter() {
            super(R.layout.blu_item_layout_bluetooth_on);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, @NonNull SearchResult item) {
            helper.setText(R.id.tv_title, item.getName());
            helper.setText(R.id.tv_text, item.getAddress());
        }
    }

    /**
     * 可用设备
     */
    static class UnAdapter extends BaseQuickAdapter<SearchResult, BaseViewHolder> {

        private UnAdapter() {
            super(R.layout.blu_item_layout_bluetooth_un);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, @NonNull SearchResult item) {
            helper.setText(R.id.tv_title, item.getAddress());
        }
    }

}
